package com.shunhao.utils

import android.content.Context
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.CharacterStyle
import android.text.style.ForegroundColorSpan

/**
 * Created by lmt on 16/9/14.
 *
 * @author 康贵阳
 */
class StringFormatUtil(private val mContext: Context,
                       private val wholeStr: String,
                       private val highlightStr: String,
                       private var color: Int) {

    private var spBuilder: SpannableStringBuilder? = null
    private var start = 0
    private var end = 0

    /**
     * 着色
     *
     * @return
     */
    fun fillColor(): StringFormatUtil? {
        if (!TextUtils.isEmpty(wholeStr) && !TextUtils.isEmpty(highlightStr)) {
            if (wholeStr.contains(highlightStr)) {
                start = wholeStr.indexOf(highlightStr)
                end = start + highlightStr.length
            } else {
                return null
            }
        } else {
            return null
        }
        spBuilder = SpannableStringBuilder(wholeStr)
        color = mContext.resources.getColor(color)
        val charaStyle: CharacterStyle = ForegroundColorSpan(color)
        spBuilder!!.setSpan(charaStyle, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return this
    }

    val result: SpannableStringBuilder?
        get() = if (spBuilder != null) {
            spBuilder
        } else null

}